package com.fdb.efp.console.api.rest;


import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.ApplicationConstance;
import com.irdstudio.basic.framework.core.constant.PubConstant;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.efp.console.service.facade.TlrInfoService;
import com.irdstudio.efp.console.service.vo.TlrInfoVO;
import com.irdstudio.efp.esb.service.bo.req.sed.pls.ReqQueryTellerInfoBean;
import com.irdstudio.efp.esb.service.bo.resp.pls.RespQueryTellerInfoBean;
import com.irdstudio.efp.esb.service.facade.sed.pls.QueryTellerInfoService;
import com.irdstudio.efp.flow.service.facade.InstFlowProcessService;
import com.irdstudio.efp.flow.service.vo.InstFlowProcessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.service.facade.SUserService;
import com.irdstudio.efp.console.service.vo.SUserDutyVO;
import com.irdstudio.efp.console.service.vo.SUserRoleVO;
import com.irdstudio.efp.console.service.vo.SUserVO;
import com.irdstudio.efp.e4a.service.facade.SRoleDataRuleService;
import com.irdstudio.efp.flow.service.facade.BizFlowEngineInquireService;
import com.irdstudio.basic.framework.core.constant.DataRuleType;
import com.irdstudio.basic.framework.core.constant.ResponseData;
import com.irdstudio.basic.framework.web.controller.AbstractController;

@RestController
@RequestMapping("/api")
public class SUserController extends AbstractController {

	@Autowired
	@Qualifier("sUserService")
	private SUserService sUserService;

	@Autowired
	@Qualifier("bizFlowEngineInquireService")
	private BizFlowEngineInquireService bizFlowEngineInquireService;

	@Autowired
	@Qualifier("sRoleDataRuleService")
	private SRoleDataRuleService sRoleDataRuleService;

	@Autowired
	@Qualifier("queryTellerInfoService")
	private QueryTellerInfoService queryTellerInfoService;

	@Autowired
	@Qualifier("instFlowProcessService")
	private InstFlowProcessService instFlowProcessService;

	@Autowired
	@Qualifier("tlrInfoService")
	private TlrInfoService tlrInfoService;

	/**
	 * 列表数据查询
	 */
	@PostMapping(path = "/s/users")
	public @ResponseBody ResponseData<List<SUserVO>> querySUserAll(@RequestBody SUserVO vo) {
		List<SUserVO> outputVo = null;
		// 根据用户角色获取用户权限方案
		Map<String, String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(),
				getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null : dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType
				.getDataRuleType(dataRuleTypeMap == null ? null : dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);
		// 根据权限方案调用不同的方案进行数据查询
		switch (dataRuleType) {
		case Owner:
			outputVo = sUserService.queryAllOwner(vo);
			break;
		case CurrOrg:
			outputVo = sUserService.queryAllCurrOrg(vo);
			break;
		case CurrDownOrg:
			outputVo = sUserService.queryAllCurrDownOrg(vo);
			break;
		default:
			outputVo = sUserService.queryAllOwner(vo);
			break;
		}
		return getResponseData(outputVo);

	}

	/**
	 * 制定法人机构列表数据查询
	 */
	@RequestMapping(value = "/s/users/org", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<SUserVO>> queryAllOrgByPage(@RequestBody SUserVO vo) {
		setUserInfoToVO(vo);
		List<SUserVO> outputVo = sUserService.queryAllOrgByPage(vo);
		return getResponseData(outputVo);

	}

	@RequestMapping(value = "/s/colt/users", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<SUserVO>> queryColtUserByPage(@RequestBody SUserVO vo) {
		setUserInfoToVO(vo);
		List<SUserVO> outputVo = sUserService.queryColtUserByPage(vo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键查询详情
	 */
	@RequestMapping(value = "/s/user/{userCode}", method = RequestMethod.POST)
	public @ResponseBody ResponseData<SUserVO> queryByPk(@PathVariable("userCode") String userCode) {
		SUserVO inVo = new SUserVO();
		inVo.setUserCode(userCode);
		SUserVO outputVo = sUserService.queryByPk(inVo);
		return getResponseData(outputVo);
	}

	/**
	 * 查询柜员详情
	 */
	@RequestMapping(value = "/s/isTeller", method = RequestMethod.POST)
	public @ResponseBody
	ResponseData<SUserVO> queryByTeller(@RequestBody SUserVO inSUserVo) {
		logger.info("开始新增用户信息的流程，从前台得到的信息为：" + JSONObject.toJSONString(inSUserVo));
		SUserVO outputVo = new SUserVO();
		try {
			if ("Y".equals(inSUserVo.getIsTeller())) {
				logger.info("新增用户是柜员用户，调用统一柜员管理系统的“柜员信息查询”接口来获取信息！");
				ReqQueryTellerInfoBean reqQueryTellerInfoBean = new ReqQueryTellerInfoBean();
				reqQueryTellerInfoBean.setTxnVrty("MS2009");
				reqQueryTellerInfoBean.setUsrID("90087");
				reqQueryTellerInfoBean.setTlrCd(inSUserVo.getUserCode());
				RespQueryTellerInfoBean respQueryTellerInfoBean = null;
				logger.info("开始查询柜员用户的信息！查询条件为：" + JSONObject.toJSONString(reqQueryTellerInfoBean));
				respQueryTellerInfoBean = queryTellerInfoService.queryTellerInfo(reqQueryTellerInfoBean);
				logger.info("查询柜员用户结果为：" + JSONObject.toJSONString(respQueryTellerInfoBean));
				if (Objects.nonNull(respQueryTellerInfoBean)) {
					logger.info("根据查询结果，开始组装柜员用户信息！");
					//柜员工号
					outputVo.setUserCode(respQueryTellerInfoBean.getTlrCd());
					outputVo.setUserName(respQueryTellerInfoBean.getTlrNm());
					outputVo.setIdCardNo(respQueryTellerInfoBean.getTlrId());
					outputVo.setOrgCode(respQueryTellerInfoBean.getTlrAtchOrgNo());
					outputVo.setOwnBranch(respQueryTellerInfoBean.getTlrAtchBrNo());
					outputVo.setIsUseFingerprint(respQueryTellerInfoBean.getTlrUsedFngrPrntFlg());
					outputVo.setTellerLevel(respQueryTellerInfoBean.getTlrLvl());
					outputVo.setTellerCategory(respQueryTellerInfoBean.getTlrTp());
					outputVo.setIsTeller("Y");
					logger.info("组装柜员用户信息结束！");
				}
			} else {
				logger.info("新增用户是非柜员用户，查询个贷同步的数据来获取用户信息！");
				TlrInfoVO intlrInfoVO = new TlrInfoVO();
				intlrInfoVO.setTlrno(inSUserVo.getUserCode());
				TlrInfoVO queryTlrInfoRs = tlrInfoService.queryByPk(intlrInfoVO);
//				outputVo = sUserService.queryByPk(inSUserVo);
				if (Objects.isNull(queryTlrInfoRs))
					return ResponseData.create(null, ApplicationConstance.FAILURE, "查询个贷同步的数据结果为空，请手动输入想要新增的客户信息！", false);
				//拼接数据
				outputVo.setUserCode(queryTlrInfoRs.getTlrno());
				outputVo.setUserName(queryTlrInfoRs.getTlrName());
				outputVo.setOrgCode(queryTlrInfoRs.getBrcode());
				outputVo.setEmail(queryTlrInfoRs.getEmail());
				outputVo.setStatus(queryTlrInfoRs.getStatus());
				outputVo.setIsTeller("N");
				logger.info("查询同步个贷数据的结果是：" + JSONObject.toJSONString(outputVo));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("处理失败：" + e.getMessage());
			return ResponseData.create(null, ApplicationConstance.FAILURE, e.getMessage(), false);
		}
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键查询详情
	 */
	@RequestMapping(value = "/s/user/pwd", method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> queryByPkss(@RequestBody SUserVO inSUserVo) {
		setUserInfoToVO(inSUserVo);
		int outputVo = sUserService.pwdByPk(inSUserVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键删除信息 【变更】 只是注销，没在库中删除，将状态设置为“注销” 0
	 */
	@RequestMapping(value = "/s/user", method = RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody SUserVO inSUserVo) {
		setUserInfoToVO(inSUserVo);
		// 查询注销用户是否又待处理的任务
		InstFlowProcessVO instFlowProcessVO = new InstFlowProcessVO();
		instFlowProcessVO.setProcessUserId(inSUserVo.getUserCode());
		instFlowProcessVO.setProcessUserName(inSUserVo.getUserName());
		instFlowProcessVO.setProcessOrgId(inSUserVo.getOrgCode());
		instFlowProcessVO.setProcessOrgName(inSUserVo.getOrgName());
		int outputVo = instFlowProcessService.queryByUserInfo(instFlowProcessVO);
		if (outputVo>0){
			/** 将状态设置为“待停用” */
			inSUserVo.setStatus(ConsoleConstant.USER_STATUS_2);
		}else{
			/** 将状态设置为“注销” */
			inSUserVo.setStatus(ConsoleConstant.USER_STATUS_0);
		}
		outputVo = sUserService.updateByPk(inSUserVo);
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键更新信息
	 * 
	 * @param inSUserVo
	 */
	@RequestMapping(value = "/s/user", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody SUserVO inSUserVo) {
		setUserInfoToVO(inSUserVo);
		int outputVo = sUserService.updateByPk(inSUserVo);
		return getResponseData(outputVo);

	}
	
	/**
	 * 新增数据
	 * 
	 * @param inSUserVo
	 */
	@RequestMapping(value = "/s/user", method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertSUser(@RequestBody SUserVO inSUserVo) {
		setUserInfoToVO(inSUserVo);
		int outputVo = sUserService.insertSUser(inSUserVo);
		return getResponseData(outputVo);
	}
	/**
	 * 新增修改数据
	 * 
	 * @param inSUserVo
	 */
	@RequestMapping(value = "/s/user/inOrUp", method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertByPk(@RequestBody SUserVO inSUserVo) {
		setUserInfoToVO(inSUserVo);
		int outputVo = sUserService.insertOrUpdateByPk(inSUserVo);
		return getResponseData(outputVo);
	}

	@RequestMapping(value = "/s/user/inOrUp", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> UpdateByPk(@RequestBody SUserVO inSUserVo) {
		setUserInfoToVO(inSUserVo);
		int outputVo = sUserService.insertOrUpdateByPk(inSUserVo);
		return getResponseData(outputVo);
	}
	/**
	 * 给用户新增岗位
	 */
	@RequestMapping(value = "/s/userDuty", method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> setUserDuty(@RequestBody SUserDutyVO sUserDutyVO) {
		setUserInfoToVO(sUserDutyVO);
		int outputVo = sUserService.setUserDuty(sUserDutyVO);
		return getResponseData(outputVo);

	}

	/**
	 * 给用户新增角色
	 */
	@RequestMapping(value = "/s/userRole", method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> setUserRole(@RequestBody SUserRoleVO sUserRoleVO) {
		setUserInfoToVO(sUserRoleVO);
		int outputVo = sUserService.setUserRole(sUserRoleVO);
		return getResponseData(outputVo);

	}

	/**
	 * 根据查询条件 查询用户
	 * 
	 * @param sUserRoleVO
	 * @return
	 */
	@RequestMapping(value = "/s/users/condition", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<SUserVO>> queryUsersByConditio(@RequestBody SUserVO sUserVO) {
		List<SUserVO> outputVo = sUserService.queryUsersByCondition(sUserVO);
		return getResponseData(outputVo);

	}

	private ResponseData<Integer> setResponseMessage(Integer outputVo, String message) {
		ResponseData<Integer> responseData = new ResponseData<Integer>();
		responseData.setMessage(message);
		responseData.setCode(ApplicationConstance.FAILURE);
		responseData.setSuccess(true);
		return responseData;
	}

}
